<!--出库统计-->
<template>
  <div class="inout-water-container">
    <!-- 时间选择标签 -->
    <el-tabs v-model="activeTimeTab" @update:modelValue="handleTabChange">
      <el-tab-pane label="今日" name="today"></el-tab-pane>
      <el-tab-pane label="昨日" name="yesterday"></el-tab-pane>
      <el-tab-pane label="本周" name="week"></el-tab-pane>
      <el-tab-pane label="上周" name="lastWeek"></el-tab-pane>
      <el-tab-pane label="本月" name="month"></el-tab-pane>
      <el-tab-pane label="上月" name="lastMonth"></el-tab-pane>
    </el-tabs>

    <!-- 搜索条件框 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-row :gutter="20" class="search-row">
        <el-col :span="6">
          <el-form-item label="出库单号">
            <el-input v-model="searchForm.orderNumber" placeholder="请输入出库单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仓库名称">
            <el-select v-model="searchForm.warehouse" placeholder="请选择" style="width:200px">
              <el-option v-for="item in warehouses" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库类型">
            <el-select 
              v-model="searchForm.outType" 
              placeholder="请选择" 
              style="width:200px"
              clearable>
              <el-option 
                v-for="item in outTypes" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：出库日期 -->
      <el-row :gutter="20" class="search-row">
        <el-col :span="6">
          <el-form-item label="出库日期">
            <el-date-picker 
              v-model="searchForm.dateRange" 
              type="daterange" 
              range-separator="至" 
              start-placeholder="开始日期" 
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="制单日期">
            <el-date-picker 
              v-model="searchForm.createTimeRange" 
              type="daterange" 
              range-separator="至" 
              start-placeholder="开始日期" 
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：重置和查询按钮 -->
      <el-row :gutter="20" class="search-row">
        <el-col :span="24" class="search-buttons">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="search">查询</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="24">
        <div class="stat-group">
          <div class="stat-item">
            <p class="stat-value green">{{ statData.totalOrder || 0 }}</p>
            <p class="stat-label">出库单数量</p>
          </div>
          <div class="stat-item">
            <p class="stat-value green">{{ statData.totalAmount.toFixed(2) }}</p>
            <p class="stat-label">出库金额</p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-row :gutter="20" class="action-row">
      <el-col :span="24" class="action-buttons">
        <el-button @click="exportData">导出</el-button>
        <el-button @click="refreshData">刷新</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table :data="tableData" :border="false" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" ></el-table-column>
      <el-table-column prop="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="out_code" label="出库单号" width="190"></el-table-column>
      <el-table-column prop="out_date" label="出库日期" width="190"></el-table-column>
      <el-table-column prop="out_type" label="出库类型" width="120" :formatter="formatOutType"></el-table-column>
      <el-table-column prop="wh_id" label="仓库名称" width="120" :formatter="formatWarehouse"></el-table-column>
      <el-table-column prop="out_num" label="出库数量" width="120"></el-table-column>
      <el-table-column prop="out_total" label="出库金额" width="120" :formatter="formatCurrency"></el-table-column>
      <el-table-column prop="out_user" label="经办人" ></el-table-column>
      <el-table-column prop="create_name" label="制单人"></el-table-column>
      <el-table-column prop="create_time" label="制单时间"></el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination 
        :current-page="currentPage"
        :page-size="pageSize" 
        :pager-count="11" 
        layout="prev, pager, next, jumper" 
        :total="totalCount"
        @current-change="handleCurrentChange" 
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';

export default {
  setup() {
    const activeTimeTab = ref('today');
    const searchForm = reactive({
      orderNumber: '',
      warehouse: '',
      outType: '',
      dateRange: [],
      createTimeRange: []
    });
    
    const tableData = ref([]);
    const statData = reactive({
      totalAmount: 0,
      totalOrder: 0,
      totalQuantity: 0
    });
    
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalCount = ref(0);
    const loading = ref(false);
    
    const warehouses = ref([]);
    const outTypes = ref([]);

    // 获取出库类型（从API获取）
    const fetchOutTypes = async () => {
      try {
        const response = await http.get('/BusinessType/GetBusinessTypes?field=出库');
        outTypes.value = response.data.map(item => ({
          value: item.bus_name,
          label: item.bus_name
        }));
      } catch (error) {
        console.error('获取出库类型失败:', error);
        ElMessage.error('获取出库类型失败');
      }
    };

    // 获取仓库列表
    const fetchWarehouses = async () => {
      try {
        const response = await http.get('/Warehouse/GetWarehouses');
        warehouses.value = response.data;
      } catch (error) {
        console.error('获取仓库列表失败:', error);
        ElMessage.error('获取仓库列表失败');
      }
    };

    // 格式化出库类型
    const formatOutType = (row, column, cellValue) => {
      const type = outTypes.value.find(item => item.value === cellValue);
      return type ? type.label : cellValue;
    };

    // 格式化仓库名称
    const formatWarehouse = (row, column, cellValue) => {
      const warehouse = warehouses.value.find(item => item.wh_id === cellValue);
      return warehouse ? warehouse.wh_name : cellValue;
    };

    // 格式化金额
    const formatCurrency = (row, column, cellValue) => {
      return parseFloat(cellValue || 0).toFixed(2);
    };

    // 获取默认时间范围
    const getDefaultTimeRange = (timeType) => {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      
      switch (timeType) {
        case 'today':
          return {
            start: formatDate(today),
            end: formatDate(today)
          };
        case 'yesterday': {
          const yesterday = new Date(today.getTime() - 86400000);
          return {
            start: formatDate(yesterday),
            end: formatDate(yesterday)
          };
        }
        case 'week': {
          const firstDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay()));
          const lastDayOfWeek = new Date(firstDayOfWeek);
          lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
          return {
            start: formatDate(firstDayOfWeek),
            end: formatDate(lastDayOfWeek)
          };
        }
        case 'lastWeek': {
          const firstDayOfLastWeek = new Date(today.setDate(today.getDate() - today.getDay() - 7));
          const lastDayOfLastWeek = new Date(firstDayOfLastWeek);
          lastDayOfLastWeek.setDate(firstDayOfLastWeek.getDate() + 6);
          return {
            start: formatDate(firstDayOfLastWeek),
            end: formatDate(lastDayOfLastWeek)
          };
        }
        case 'month': {
          const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
          const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
          return {
            start: formatDate(firstDayOfMonth),
            end: formatDate(lastDayOfMonth)
          };
        }
        case 'lastMonth': {
          const firstDayOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
          const lastDayOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
          return {
            start: formatDate(firstDayOfLastMonth),
            end: formatDate(lastDayOfLastMonth)
          };
        }
        default:
          return null;
      }
    };

    // 格式化日期
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    // 格式化日期时间
    const formatDateTime = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    // 获取数据
    const fetchData = async () => {
      loading.value = true;
      try {
        let defaultTimeRange = null;
        if (activeTimeTab.value !== 'custom') {
          defaultTimeRange = getDefaultTimeRange(activeTimeTab.value);
        }
     
        const params = {
          timeType: activeTimeTab.value !== 'custom' ? activeTimeTab.value : null,
          code: searchForm.orderNumber || null,
          whid: searchForm.warehouse || null,
          instarttime: searchForm.dateRange 
            ? searchForm.dateRange[0] 
            : (defaultTimeRange ? defaultTimeRange.start : null),
          inendtime: searchForm.dateRange 
            ? searchForm.dateRange[1] 
            : (defaultTimeRange ? defaultTimeRange.end : null),
          starttime: searchForm.createTimeRange ? searchForm.createTimeRange[0] : null,
          endtime: searchForm.createTimeRange ? searchForm.createTimeRange[1] : null,
          outtype: searchForm.outType || null,
          page: currentPage.value,
          pagesize: pageSize.value
        };
    
        const response = await http.get('/Outstock_h/Outstock_hTJ', { params });
        
        tableData.value = response.data.list.map((item, index) => ({
          ...item,
          selected: false,
          index: (currentPage.value - 1) * pageSize.value + index + 1,
          out_num: parseInt(item.out_num || 0),
          out_total: parseFloat(item.out_total || 0),
          // 格式化日期时间字段
          out_date: formatDateTime(item.out_date),
          create_time: formatDateTime(item.create_time),
          approver_time: item.approver_time ? formatDateTime(item.approver_time) : ''
        }));
        
        totalCount.value = response.data.total;
        
        // 统计信息
        statData.totalAmount = response.data.out_total || 0;
        statData.totalOrder = response.data.total || 0;
        statData.totalQuantity = response.data.out_num || 0;
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 时间标签切换
    const handleTabChange = (name) => {
      activeTimeTab.value = name;
      currentPage.value = 1;
      fetchData();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        orderNumber: '',
        warehouse: '',
        outType: '',
        dateRange: [],
        createTimeRange: []
      });
      currentPage.value = 1;
      fetchData();
    };

    // 查询
    const search = () => {
      // 如果是自定义时间，但未选择时间范围，给出提示
      if (activeTimeTab.value === 'custom' && (!searchForm.dateRange || !searchForm.dateRange[0] || !searchForm.dateRange[1])) {
        ElMessage.warning('请选择自定义时间范围');
        return;
      }
      
      currentPage.value = 1;
      fetchData();
    };

    // 刷新数据
    const refreshData = () => {
      fetchData();
    };

    const multipleSelection = ref([]);
 
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
    // 导出数据
const exportData = () => {
  // 获取选中的行
  const selectedRows = tableData.value.filter(item => item.selected);
  
  // 如果没选，提示
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要导出的单据！');
    return;
  }
  
  // 1. 组装表头和数据
  const header = [
    '出库单号', '出库日期', '出库类型', '仓库名称', '出库数量', 
    '出库金额', '经办人', '制单人', '制单时间', '审核人', '审核时间'
  ];
  const data = [];
 
  selectedRows.forEach(main => {
    data.push([
      main.out_code,
      main.out_date, // 已经是格式化后的日期
      formatOutType({}, {}, main.out_type),
      formatWarehouse({}, {}, main.wh_id),
      main.out_num,
      formatCurrency({}, {}, main.out_total),
      main.out_user,
      main.create_name,
      main.create_time, // 已经是格式化后的时间
      main.approver_name,
      main.approver_time // 已经是格式化后的时间
    ]);
  });
 
  // 2. 生成 worksheet 和 workbook
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '出库统计');
 
  // 3. 导出
  XLSX.writeFile(wb, '出库统计.xlsx');
};
 
// 在表格中添加选中状态
const toggleRowSelection = (row) => {
  // 使用$set确保响应式更新
  row.selected = !row.selected;
  // 强制更新视图（可选，取决于Vue的响应式系统）
  tableData.value = [...tableData.value];
};
    // 分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchData();
    };

    // 当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchData();
    };

    // 初始化加载数据
    onMounted(() => {
      fetchWarehouses();
      fetchOutTypes();
      fetchData();
    });

    return {
      activeTimeTab,
      searchForm,
      tableData,
      statData,
      currentPage,
      toggleRowSelection,
      pageSize,
      totalCount,
      loading,
      warehouses,
      outTypes,
      handleTabChange,
      resetSearch,
      search,
      refreshData,
      exportData,
      handleSizeChange,
      handleCurrentChange,
      formatOutType,
      formatWarehouse,
      formatCurrency,
      handleSelectionChange
    };
  }
};
</script>

<style scoped>
.inout-water-container {
  width: 100%;
  padding: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.product-info {
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  text-align: left;
}

.product-info span {
  margin-right: 20px;
}

/* 确保表单元素左对齐 */
.search-form .el-form-item {
  display: flex;
  align-items: center;
}

.search-form .el-form-item__content {
  margin-left: 0 !important;
  flex: 1;
}
.search-form {
  margin-bottom: 20px;
  text-align: left;
}

.search-row {
  margin-bottom: 10px;
}
.stat-row {
  width: 100%;
  margin: 0;
  margin-bottom: 20px;
}

.search-buttons {
  text-align: left;
}

.stat-group {
  display: flex;
  padding: 15px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.green {
  color: #409eff;
}

.blue {
  color: #409eff;
}

.orange {
  color: #e6a23c;
}

.action-row {
  margin-bottom: 20px;
}

.action-buttons {
  text-align: left;
}

.el-table {
  margin-top: 20px;
}
</style>
